<template>
  <BaseDialog
    :title="(!props.item.messageId ? '新增' : '查看') + '信息发布配置'"
    :handleCancel="handleCancel"
    :dialogVisible="props.dialogVisible"
    width="1100px"
  >
    <el-form
      :class="props.item.messageId ? 'detail' : ''"
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="100px"
      class="demo-ruleForm"
      status-icon
      @submit="submitForm"
    >
      <el-row :gutter="20">
        <el-col :span="11" style="border-right: 1px solid #ddd">
          <el-form-item label="标题" prop="title">
            <el-input placeholder="请输入标题" type="text" v-model="ruleForm.title" />
          </el-form-item>
          <el-form-item label="发布时间" prop="publishTime">
            <el-date-picker
              style="width: 50%"
              v-model="ruleForm.publishTime"
              type="date"
              @change="dateChange"
              :teleported="false"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              :disabled-date="disabledDate"
              placeholder="请选择日期"
            />
            <el-time-picker
              style="width: 48%; margin-left: 7px"
              v-model="ruleForm.time"
              value-format="HH:mm"
              format="HH:mm"
              :teleported="false"
              :disabled-hours="disabledHour"
              :disabled-minutes="disabledMinute"
              placeholder="请选择时间"
              :clearable="false"
            />
          </el-form-item>
          <el-form-item label="素材" prop="materialNames">
            <el-input
              ref="selectPop"
              :placeholder="!props.item.messageId ? '请选择素材，多选' : ''"
              @click="selectMateria"
              v-model="ruleForm.materialNames"
              readonly
            />
            <MaterialTable
              size="small"
              style="margin-top: 4px"
              v-if="materialList.length > 0"
              v-model:tableData="materialList"
            />
          </el-form-item>
        </el-col>
        <el-col :span="13">
          <el-form-item label="发送对象" prop="publishToList">
            <el-checkbox-group v-model="ruleForm.publishToList">
              <el-checkbox label="1">好友</el-checkbox>
              <el-checkbox label="2">群聊</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <FriendsTable
            v-if="ruleForm.publishToList.includes('1')"
            style="margin-top: 4px"
            v-model:tableData="ruleForm.friendsList"
          />

          <GroupTable
            v-if="ruleForm.publishToList.includes('2')"
            style="margin-top: 4px"
            v-model:tableData="ruleForm.groupList"
          >
          </GroupTable>
        </el-col>
      </el-row>
      <div class="form-btn" v-if="!props.item.messageId">
        <el-button @click="handleCancel"> 取 消 </el-button>
        <el-button type="primary" :loading="btnLoading" native-type="submit"> 确 定 </el-button>
      </div>
    </el-form>
  </BaseDialog>
  <SelectMaterial
    v-if="visibleMaterial"
    v-model:dialogVisible="visibleMaterial"
    v-model:selecedList="materialList"
    :item="item"
    title="选择素材"
  ></SelectMaterial>
</template>
<script setup lang="ts">
import MaterialTable from './components/MaterialTable.vue';
import FriendsTable from './components/FriendsTable.vue';
import GroupTable from './components/GroupTable.vue';
import type { FormInstance } from 'element-plus';
import { contentManagementService } from '@/api/contentManagement';
import SelectMaterial from '@/components/selectMaterial/index.vue';
import { basicConfigService } from '@/api/basicConfig';
import moment from 'moment';
const props = defineProps({
  dialogVisible: {
    type: Boolean,
  },
  item: {
    type: Object,
  },
  handleSearch: {
    type: Function,
  },
  type: {
    type: String,
  },
});
const materialList = ref([]);
const ruleFormRef = ref<FormInstance>();
const ruleForm = ref({
  title: '',
  publishTime: '',
  publishToList: [],
  materialNames: '',
  friendsList: [],
  groupList: [],
  time: undefined,
});
watch(
  () => materialList.value,
  (val) => {
    ruleForm.value.materialNames = val.map((e) => e.materialName).join(',');
  },
);
watch(ruleForm.value.friendsList, () => {
  ruleFormRef.value.clearValidate('friendsList');
});
watch(ruleForm.value.groupList, () => {
  ruleFormRef.value.clearValidate('groupList');
});

const rules = reactive({
  title: [{ required: true, message: '请输入', trigger: 'change' }],
  publishTime: [{ required: true, message: '请选择', trigger: 'change' }],
  materialNames: [{ required: true, message: '请选择', trigger: 'change' }],
  publishToList: [{ required: true, message: '请选择', trigger: 'change' }],
  friendsList: [{ required: true, message: '请选择', trigger: 'change' }],
  groupList: [{ required: true, message: '请选择', trigger: 'change' }],
});
const btnLoading = ref(false);
const emit = defineEmits(['update:dialogVisible']);
const visibleMaterial = ref(false);
const selectPop = ref(null);
watch(visibleMaterial, (val) => {
  if (val) selectPop.value.blur();
});

const selectMateria = () => {
  visibleMaterial.value = true;
};
const submitForm = (e) => {
  e.preventDefault();
  ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      btnLoading.value = true;
      const friendsList = ruleForm.value.friendsList.map((e) => {
        return {
          publishTo: 1,
          bizId: e.wxUserId,
          relationRobotId: e.wxRobotId,
          relationRobotName: e.managerName,
        };
      });
      const groupList = ruleForm.value.groupList.map((e) => {
        return {
          publishTo: 2,
          bizId: e.wxGroupCode,
        };
      });
      contentManagementService
        .publishMessageAdd({
          data: {
            title: ruleForm.value.title,
            publishTime: ruleForm.value.publishTime + ' ' + ruleForm.value.time + ':00',
            materialIds: materialList.value.map((e) => e.materialId),
            publishToList: ruleForm.value.publishToList,
            userDtoList: [...friendsList, ...groupList],
          },
        })
        .then(() => {
          btnLoading.value = false;
          ElMessage({
            message: '保存成功',
            type: 'success',
          });
          handleCancel();
          props.handleSearch();
        })
        .catch(() => {
          btnLoading.value = false;
        });
    } else {
      console.log('error submit!', fields);
    }
  });
};
const model = ref({
  hour1: 0,
  hour2: 0,
  minute1: 0,
  minute2: 0,
  defaultHour: 0,
  defaultMinute: 0,
});
const disabledDate = (time) => {
  // 禁止选择今天以前的时间
  let num = 0;
  if (new Date().getHours() < model.value.hour2) num = 8.64e7;
  return time.getTime() < Date.now() - num;
};
const dateChange = () => {
  filterTime();
  ruleForm.value.time = '';
};
const makeRange = (start: number, end: number) => {
  const result: number[] = [];
  for (let i = start; i <= end; i++) {
    result.push(i);
  }
  return result;
};
const isNowDay = computed(
  () => moment().format('YYYY-MM-DD') === moment(ruleForm.value.publishTime).format('YYYY-MM-DD'),
);
const filterTime = () => {
  const nowHour = new Date().getHours();
  const nowMinutes = new Date().getMinutes();
  if (isNowDay.value && nowHour > model.value.hour1 && nowHour <= model.value.hour2) {
    model.value.hour1 = nowHour;
    model.value.minute1 = nowMinutes;
  } else {
    model.value.hour1 = model.value.defaultHour;
    model.value.minute1 = model.value.defaultMinute;
  }
};
const disabledHour = () => {
  if (!ruleForm.value.publishTime) return;
  return makeRange(0, model.value.hour1 - 1).concat(makeRange(model.value.hour2 + 1, 23));
};
const disabledMinute = (hour) => {
  if (!ruleForm.value.publishTime) return;
  if (hour === model.value.hour1) {
    return makeRange(0, model.value.minute1 - (isNowDay.value ? 0 : 1));
  }
  if (hour === model.value.hour2) {
    return makeRange(model.value.minute2 + 1, 59);
  }
};

const getConfigInfo = () => {
  basicConfigService.getConfigInfo({ data: {} }).then((res) => {
    const { publishTimeEnd, publishTimeStart } = res.data;
    model.value.hour1 = Number(publishTimeStart.split(':')[0]);
    model.value.defaultHour = Number(publishTimeStart.split(':')[0]);
    model.value.minute1 = Number(publishTimeStart.split(':')[1]);
    model.value.defaultMinute = Number(publishTimeStart.split(':')[1]);
    model.value.hour2 = Number(publishTimeEnd.split(':')[0]);
    model.value.minute2 = Number(publishTimeEnd.split(':')[1]);
  });
};
const handleCancel = () => {
  emit('update:dialogVisible', false);
};
onMounted(() => {
  getConfigInfo();
});
</script>
<style lang="scss" scoped>
.detail {
  :deep(.el-form-item__label:before) {
    content: ' ' !important;
  }
}
.right {
  & > :deep(.el-form-item__label) {
    width: auto !important;
  }
}
:deep(.el-input__validateIcon) {
  display: none;
}
.files {
  display: flex;
  font-size: 12px;
  .name {
    flex: 1;
    width: 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
:deep(.el-input__wrapper) {
  width: 100%;
  box-sizing: border-box;
}
</style>
